package com.pilot.game.service;

import com.pilot.game.config.ApplicationProperties;
import com.qiniu.util.Json;
import okhttp3.*;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

/**
 * SmsServices
 *
 * @author yhq
 * @version 2017/12/24 下午3:30
 */
@Service
public class SmsServices {

    private final Logger log = LoggerFactory.getLogger(UserService.class);

    private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");

    private final ApplicationProperties.SMS properties;

    private final CacheManager cacheManager;

    public SmsServices(ApplicationProperties properties, CacheManager cacheManager) {
        this.properties = properties.getSms();
        this.cacheManager = cacheManager;
    }

    /**
     * 发送短信验证码
     *
     * @param mobile 手机号码
     * @return result
     */
    public boolean sendSmsMsg(String mobile) {
        log.info("com.pilot.game.service.SmsServices.sendSmsMsg time:{} mobile:{}", Instant.now(), mobile);
        if (StringUtils.isBlank(mobile)) {
            log.info("mobile number is blank");
            return false;
        }
        String randomNumeric = RandomStringUtils.randomNumeric(4);
        Map<String, String> params = new HashMap<>(10);
        params.put("Account", properties.getAccount());
        params.put("Pwd", properties.getToken());
        params.put("Content", randomNumeric);
        params.put("Mobile", mobile);
        params.put("TemplateId", properties.getTemplateId());
        params.put("SignId", properties.getSignId());
        log.debug("request mobile is {} Content is: {}", mobile, randomNumeric);

        try {
            OkHttpClient client = new OkHttpClient();

            RequestBody body = RequestBody.create(JSON_TYPE, Json.encode(params));
            Request request = new Request.Builder()
                .url(properties.getUrl() + "SmsService/Template")
                .post(body)
                .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            log.info(result);
            cacheManager.getCache("SMS").put(mobile, randomNumeric);
            return true;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }


    /**
     * 发送普通短信
     *
     * @param mobile 手机号码
     * @return result
     */
    public boolean sendSmsMsg(String mobile, String msgContent) {
        log.info("com.pilot.game.service.SmsServices.sendSmsMsg time:{} mobile:{} msgContent:{}", Instant.now(), mobile, msgContent);
        if (StringUtils.isBlank(mobile) && StringUtils.isNotBlank(msgContent)) {
            log.info("mobile number or content is blank");
            return false;
        }
        Map<String, String> params = new HashMap<>(10);
        params.put("Account", properties.getAccount());
        params.put("Pwd", properties.getToken());
        params.put("Content", msgContent);
        params.put("Mobile", mobile);
        params.put("SignId", properties.getSignId());
        log.debug("request mobile is {} Content is: {}", mobile, msgContent);

        try {
            OkHttpClient client = new OkHttpClient();

            RequestBody body = RequestBody.create(JSON_TYPE, Json.encode(params));
            Request request = new Request.Builder()
                .url(properties.getUrl() + "SmsService/Send")
                .post(body)
                .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            log.info(result);
            return true;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 发送语音验证码
     *
     * @param mobile 手机号码
     * @return result
     */
    public boolean sendSmsVoice(String mobile) {
        log.info("com.pilot.game.service.SmsServices.sendSmsVoice time:{} mobile:{}", Instant.now(), mobile);
        if (StringUtils.isBlank(mobile)) {
            log.info("mobile number is blank");
            return false;
        }
        String randomNumeric = RandomStringUtils.randomNumeric(4);
        Map<String, String> params = new HashMap<>(10);
        params.put("Account", properties.getAccount());
        params.put("Pwd", properties.getToken());
        params.put("Content", randomNumeric);
        params.put("Mobile", mobile);
        log.debug("request mobile is {} Content is: {}", mobile, randomNumeric);

        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody body = RequestBody.create(JSON_TYPE, Json.encode(params));
            Request request = new Request.Builder()
                .url(properties.getUrl() + "SmsService/Voice")
                .post(body)
                .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            log.info(result);
            return true;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 发送语音验证码
     *
     * @return result
     */
    public String getSmsMsgHistory() {
        log.info("com.pilot.game.service.SmsServices.getSMSMsgHistory time:{}", Instant.now());

        Map<String, String> params = new HashMap<>(10);
        params.put("Account", properties.getAccount());
        params.put("Pwd", properties.getToken());

        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody body = RequestBody.create(JSON_TYPE, Json.encode(params));
            Request request = new Request.Builder()
                .url(properties.getUrl() + "ReportMo/Mo")
                .post(body)
                .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            log.info(result);
            return result;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return StringUtils.EMPTY;
        }
    }

    /**
     * 查询余额
     *
     * @return result
     */
    public String getAccountBalance() {
        log.info("com.pilot.game.service.SmsServices.getAccountBalance time:{}", Instant.now());

        Map<String, String> params = new HashMap<>(10);
        params.put("Account", properties.getAccount());
        params.put("Pwd", properties.getToken());

        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody body = RequestBody.create(JSON_TYPE, Json.encode(params));
            Request request = new Request.Builder()
                .url(properties.getUrl() + "Account/Balance")
                .post(body)
                .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            log.info(result);
            return result;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return StringUtils.EMPTY;
        }
    }
}
